<?php

 	include_once("./helper.php");
	
	include_once("./config.php");

	function db_connect()
	{
		global $_u, $_p, $_h;
		
		return mysql_connect($_h, $_u, $_p);
	}
	
	db_connect();

	function db_update($table, $fields)
	{
		unset($fields["PHPSESSID"]);
	
		db_converte_dados($fields);

		$ar_fields = array_keys($fields);

		$empty_data = null;

		$new_fields = null;


		foreach($ar_fields as $key)
		{
			if(strpos($key, $table) !== false )// &&  trim($fields[$key]) != "")
			{
				$new_key = str_replace($table, "", $key);

				$new_fields[$new_key] = quote_smart($fields[$key]);
			}
		}

		$ar_fields = array_keys($new_fields);

		$tuples = "";

		$primary_key = -1;
		$primary_data = -1;
		
		if($_REQUEST['debug'])
			print_r($fields);

		foreach($ar_fields as $key)
		{
			if($primary_key == -1)
			{
				$primary_key = $key;
				$primary_data = $new_fields[$key];
			}

		 	$tuples[] = "$key = " . $new_fields[$key];
		}

		$tuples = implode(", ", $tuples);	

		$sql = "UPDATE $table SET $tuples WHERE $primary_key = $primary_data";

		$res = db_query($sql);

		return $res ? db_row($table, $primary_data) : 0;
	}


	function db_insert($table, $fields)
	{
	
		if($fields[$table . "Id"])
			return db_update($table, $fields);
		
		unset($fields["PHPSESSID"]);
		
		db_converte_dados($fields);

		$ar_fields = array_keys($fields);

		$empty_data = null;

		$new_fields = null;

		foreach($ar_fields as $key)
		{
		
			if(strpos($key, $table) !== false &&  trim($fields[$key]) != "")
			{
			
				$new_key = str_replace($table, "", $key);

				$new_fields[$new_key] = quote_smart($fields[$key]);
			}
		}

		
		$ar_fields = array_keys($new_fields);

		$sData = implode(", ", $new_fields);

		$sFields = implode(", ", $ar_fields);
		
		$sql = "INSERT INTO $table ($sFields) VALUES ($sData) ";
		
		
		$res = db_query($sql);

		
		return $res ? db_row($table, mysql_insert_id()) : 0;
	}

	function db_order($orders)
	{
		foreach($orders as $item)
		{
			$order[] = explode(':', $item);
			$i = count($order)-1;
			
			if(!isset($order[$i][1]))
				$order[$i][1] = "asc";
			else	
			if($order[$i][1] != "asc" && $order[$i][1] != "desc")
				die(); 
			
			$order[$i] = db_secure($order[$i][0]) . " " .$order[$i][1];				
		}
		
		return implode(', ', $order);
	}
	
	function db_secure($item, $like)
	{
		$sep = $like? '"' : '`';
		
		$mask = $like? '%' : '';
			
		$item = explode(',', $item);
		
		$item = $sep . $mask . implode( $sep . $mask . ',' . $mask . $sep, $item) . $mask . $sep;
		
		return $item;
	}
	
	//dont forget to open a connection before call this method
	function quote_smart($value)
	{
		// Stripslashes
		if (get_magic_quotes_gpc()) {
		
			if ($value != 'NOW()' && $value != 'null' && !is_numeric($value)) {
				$value = "'" . stripslashes($value). "'";
			}
			else
				$value = stripslashes($value);
		}
		// Quote if not integer
		else if ($value != 'NOW()' && $value != 'null' && !is_numeric($value)) {
			$value = "'" . mysql_real_escape_string($value) . "'";
			//$value = htmlentities($value);
		}
		return $value;
		
	}
	
	function prepare($query, $fields)
	{
		unset($fields["PHPSESSID"]);
		
		$ar_fields = array_keys($fields);
		
		foreach($ar_fields as $key)
		{
			if(strpos($query, "@" . $key) !== false  &&  trim($fields[$key]) != "")
			{
				$query = str_replace("@" . $key, quote_smart($fields[$key]), $query);
			}
		}
		
		return $query;
	}

	function db_select($query, $fields)
	{
		unset($fields["PHPSESSID"]);
	
		$query = prepare($query, $fields);
		//echo $query;

		return db_query($query);
	}

	function db_delete($table, $id)
	{
		$query = prepare("DELETE FROM $table WHERE Id = @Id", array("Id" => $id));
		
		return db_query($query);
	}
	
	function db_row($table, $id)
	{
		if($id > 0)
		{
			$res = db_select("SELECT * FROM $table WHERE Id = @Id", array("Id" => $id));
			$ret = mysql_fetch_array($res, MYSQL_ASSOC);
			return $ret;
		}
	}
	
	function db_scalar($query, $fields)
	{
		$res = db_select($query, $fields);
		$ret = mysql_fetch_row($res);
		return $ret[0];
	}

	function db_query($query, $fields)
	{

		try
		{
			
			if(isset($fields))
				$query = prepare($query, $fields);
					
			if($_REQUEST["debug"])
				echo "<br />\n" . $query . "\n<br />";

			global $_d;
			
			$mydb = mysql_select_db($_d);

			if(!$mydb)
				throw new Exception(mysql_error());

			$res = mysql_query($query);

			if(!$res)
				throw new Exception(mysql_error());

			return $res;
		}
		catch(Exception $e)
		{
			if($_REQUEST["debug"])
				return json_result_encode("Erro DB: " . $e->getMessage());

			return null;
		}
	}
	
	function db_converte_dados(&$fields)
	{
		$ar_fields = array_keys($fields);

		foreach($ar_fields as $key)
		{
			if(strpos($key, "Valor") != 0)
				$fields[$key] = db_formata_valor($fields[$key]);
			else if(strpos($key, "Data") != 0)
				$fields[$key] = db_formata_data($fields[$key]);
		}
	}

	function db_formata_valor($value)
	{
		$value = str_replace('.', '', $value);
		$value = str_replace(',', '.', $value);
		return $value;
	}
	
	function db_formata_data($value)
	{
		if($value == 'NOW()')
			return $value;	
		$value = str_replace('/', '-', $value);
		$value = date_format(date_create($value), 'Y-m-d');
		return $value;
	}
?>